<template>
	<view class="form-container">
	    <view class="form-item">
	      <view class="form-label">
	        <text class="required">*</text>
	        <text>业主姓名:</text>
	      </view>
	      <input class="form-input" type="text" placeholder="请输入业主姓名" v-model="formData.name" />
	    </view>
	    
	    <view class="form-item">
	      <view class="form-label">
	        <text class="required">*</text>
	        <text>站点编号</text>
	      </view>
	      <input class="form-input" type="text" placeholder="请输入站点编号" v-model="formData.station_no" />
	    </view>
	    
	    <view class="form-item"  @tap="open">
	      <view class="form-label">
	        <text class="required">*</text>
	        <text>请选择省份城市与地区:</text>
	      </view>
	      <!-- <view class="location-picker" @click="showLocationPicker">
	        <text class="location-text" v-if="formData.ptext>
	        // <view class="location-icon">🏠</view>rovince_name">	{{formData.province_name}} {{formData.city_name}} {{formData.district_name}}</text>
			 <text class="location-text" v-else>请选择</
	      </view> -->

		  <uv-form-item  @click="open">
		  
		  
		  	
		  		<view class="location-picker">
		  			<view class="location-text" v-if="formData.province_name">
		  				{{formData.province_name}} {{formData.city_name}} {{formData.district_name}}
		  			</view>
				
		  			<view class="location-text" v-else>
		  				请选择
		  			</view>
						<view class="location-icon">🏠</view>
		  		</view>
		
		  
		  	<uv-picker ref="picker" :columns="addressList" :loading="loading" keyName="name" @change="change"
		  		@confirm="confirm">
		  	</uv-picker>
		  </uv-form-item>
	    </view>
	
	     <!-- 地址选择器 -->
	      <!-- <cityPicker :column="column" :default-value="defaultValue" :mask-close-able="maskCloseAble" @confirm="confirm" @cancel="cancel" :visible="visible"/> -->
	<!-- 	  <picker mode="multiSelector" range-key='name' @columnchange="change" :value="index" :range="addressList">
		  					
								<text class="location-text" v-if="formData.province_name">	{{formData.province_name}} {{formData.city_name}} {{formData.district_name}}</text>
								 <text class="location-text" v-else>请选择</text>
		  					</picker> -->
		<view class="form-item">
	      <view class="form-label">
	        <text class="required">*</text>
	        <text>站点详细地址:</text>
	      </view>
	      <input class="form-input" type="text" placeholder="请输入站点详细地址" v-model="formData.address" />
	    </view>

<view class="upload-container">
		   <view class="upload-title">上传考评表</view>
		<view class="upload-grid">
		     
		     <view     class="upload-item" v-if="imgurlone">
		       <image 
		         :src="imgurlone" 
		      class="upload-preview"
		       ></image>
		   
		      <view class="delete-btn" @click="deleteMedias()">×</view>
		     </view>
		     
		  
		     <view 
		     
		       class="upload-item upload-add"
		       @click="chooseMediaone"
			   v-else
		     >
		       <view class="add-icon">+</view>
		       <text class="add-text">添加图片</text>
		     </view>
		   </view>
		      	 </view>
	<view class="upload-container" >
	          <view class="upload-title">上传投注站图片</view>
	          
	     
	<view class="upload-itemgrid">
				 <view class="upload-grid" 	v-for="(e,index) in imgurl.length"
						:key="index">
				    
					  <view 
				        class="upload-item"
					      v-if="imgurl[index].url"
				      >
				        <image 
				          :src="imgurl[index].url" 
				          class="upload-preview"
						  
				        ></image>
				    
				        <view class="delete-btn" @click="deleteMedia(index)">×</view>
				      </view>
				      <view 
				    
				        class="upload-item upload-add"
				        @click="chooseMedia(index)"
						v-else
				      >
				        <view class="add-icon">+</view>
				       <text class="add-text" v-if="imgurl[index].flg">正在上传</text>
				       <text class="add-text" v-else>添加图片</text>
				      </view>
				    </view>
					</view>
	      	 </view>
	
	  	  <button class="submit-button" @click="submitForm">提交</button>
	  
	  </view>
</template>

<script>
	import { Setinfo,Setupload,getarea,getstr } from '../../../api';
	const baseUrl = 'https://type-in.10906.cn/api/';
	  import cityPicker from '@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/piaoyi-cityPicker'
export default {
  data() {
    return {
		// array:[[123],[321],[12311]],
      currentTab: this.defaultActive,
      // 用于动画过渡
      transition: false,
      // 表单数据
      formData: {
        name: '',
        station_no: '',
		city_name:'',
        province_name: '',
		district_name:'',
		images:'',
        address: '',

		evaluation:'',
        type:'building'

      },
      // 星级选项
      starOptions: [],
      // 媒体文件列表
      mediaFiles: [],
	  imgurlone:'',
	 imgurl:[
		  {url:'',urls:'',flg:false},
		  {url:'',urls:'',flg:false},
		  {url:'',urls:'',flg:false},
		  {url:'',urls:'',flg:false},
		  {url:'',urls:'',flg:false},
		  {url:'',urls:'',flg:false},
		  {url:'',urls:'',flg:false},
		  {url:'',urls:'',flg:false},
	 ],
	    visible: false,
		imgflg:false,
	                  maskCloseAble: true,
	                 provinces: [], //省
	                 citys: [], //市
	                 areas: [], //区
					  column: 3,
					  str:'',
	                 pickerValue: [0, 0, 0], // 选择器默认索引
	                 defaultValue: [], // 默认地区ID（如有需要）
					 loading: true, // 加载状态
					 videoSelected: false,
					 videoPath: '',
					ceshiData: [],
					uploadResult:{},
					 
    };
  },
		computed: {
			addressList() {
				return [this.provinces, this.citys, this.areas];
			}
		},
  watch: {
    defaultActive(newVal) {
      this.currentTab = newVal;
    }
  },
  onLoad() {
	
  },
  created() {
	  this.getareas()
  },
onShow() {

},
  methods: {
	async getareas(){
		console.log('11111111111111111')
		let res=await getarea();
		if(res.code==1){
		if (res.code == 1) {
			let data = res.data
			console.log('res',res.data);
				this.provinces = data.sort((left, right) => (Number(left.id) > Number(right.id) ? 1 : -1));
				this.handlePickValueDefault()
				setTimeout(() => {
					this.loading = false
				}, 200)
		}
		}
	
	},
	handlePickValueDefault() {
		// 避免未定义报错，先判断数据是否存在
		if (!this.provinces.length) return;
		// 设置省
		this.pickerValue[0] = this.provinces.findIndex(item => Number(item.id) === this.defaultValue[0]) || 0;
		// 设置市
		this.citys = this.provinces[this.pickerValue[0]]?.children || [];
		this.pickerValue[1] = this.citys.findIndex(item => Number(item.id) === this.defaultValue[1]) || 0;
		// 设置区
		this.areas = this.citys[this.pickerValue[1]]?.children || [];
		this.pickerValue[2] = this.areas.findIndex(item => Number(item.id) === this.defaultValue[2]) || 0;
		// 重置选择器位置
		// this.$refs.picker?.setIndexs([this.pickerValue[0], this.pickerValue[1], this.pickerValue[2]], true);
	},
	change(e) {
		// if (this.loading) return;
		console.log(e)
		// let columnIndex = e.detail.column
		// let index = e.detail.value
		const {
			columnIndex,
			index,
			indexs
		} = e
		// 改变了省
		if (columnIndex === 0) {
			this.citys = this.provinces[index]?.children || []
			this.areas = this.citys[0]?.children || []
			// this.$refs.picker.setIndexs([index, 0, 0], true)
		} else if (columnIndex === 1) {
			this.areas = this.citys[index]?.children || []
			// this.$refs.picker.setIndexs(indexs, true)
		}
	},
	   open () {
	                this.visible = true
	            },
	            confirm (val) {
	                console.log(val)
					
	                this.str = JSON.stringify(val.name)
					this.formData.province_name=val.value[0].name;
					this.formData.city_name=val.value[1].name;
					this.formData.district_name=val.value[2].name;
					console.log('str',this.formData.province_name,this.formData.city_name,this.formData.district_name);
	                this.visible = false
	            },
	            cancel () {
	                this.visible = false
	            },
				getData() {
					Request({
						url: `bullbat/area/index`,
						method: 'POST',
						auth: true
					}).then(res => {
						if (res.code == 1) {
							let data = res.data
								this.provinces = data.sort((left, right) => (Number(left.id) > Number(right.id) ? 1 : -1));
								this.handlePickValueDefault()
								setTimeout(() => {
									this.loading = false
								}, 200)
						}
					})
				},
				handlePickValueDefault() {
					// 避免未定义报错，先判断数据是否存在
					if (!this.provinces.length) return;
					// 设置省
					this.pickerValue[0] = this.provinces.findIndex(item => Number(item.id) === this.defaultValue[0]) || 0;
					// 设置市
					this.citys = this.provinces[this.pickerValue[0]]?.children || [];
					this.pickerValue[1] = this.citys.findIndex(item => Number(item.id) === this.defaultValue[1]) || 0;
					// 设置区
					this.areas = this.citys[this.pickerValue[1]]?.children || [];
					this.pickerValue[2] = this.areas.findIndex(item => Number(item.id) === this.defaultValue[2]) || 0;
					// 重置选择器位置
					this.$refs.picker?.setIndexs([this.pickerValue[0], this.pickerValue[1], this.pickerValue[2]], true);
				},
				
				change(e) {
					if (this.loading) return;
					const {
						columnIndex,
						index,
						indexs
					} = e
					// 改变了省
					if (columnIndex === 0) {
						this.citys = this.provinces[index]?.children || []
						this.areas = this.citys[0]?.children || []
						this.$refs.picker.setIndexs([index, 0, 0], true)
					} else if (columnIndex === 1) {
						this.areas = this.citys[index]?.children || []
						this.$refs.picker.setIndexs(indexs, true)
					}
				},
				open() {
					this.$refs.picker.open();
					this.handlePickValueDefault()
				},
    switchTab(index) {
      if (this.currentTab === index) return;
      
      this.transition = true;
      this.currentTab = index;
      
      // 触发自定义事件
      this.$emit('change', index);
      
      // 动画结束后关闭过渡状态
      setTimeout(() => {
        this.transition = false;
      }, 300);
    },
    // 星级选择变化
    onStarChange(e) {
		// console.log('e',e.detail.value);
      this.formData.star = e.detail.value;
    },
    // 显示位置选择器
    // showLocationPicker() {
    //   // 这里可以调用uni-app的位置选择API或自定义位置选择组件
    //   // 为了演示，我们直接设置一个示例位置
    //   this.formData.location = '北京市 北京市 海淀区';
    // },
    // 提交表单
   async submitForm() {
	     console.log('表单数据11：', this.formData);
      // 表单验证
      if (!this.formData.name) {
        uni.showToast({ title: '请输入业主姓名', icon: 'none' });
        return;
      }
      if (!this.formData.station_no) {
        uni.showToast({ title: '请输入站点编号', icon: 'none' });
        return;
      }
      if (!this.formData.province_name) {
        uni.showToast({ title: '请选择省份城市与地区', icon: 'none' });
        return;
      }
      if (!this.formData.address) {
        uni.showToast({ title: '请输入站点详细地址', icon: 'none' });
        return;
      }
      if (!this.formData.images) {
        uni.showToast({ title: '请添加图片', icon: 'none' });
        return;
      }

	  if (!this.formData.evaluation){
	    uni.showToast({ title: '请上传考评表', icon: 'none' });
	    return;
	  }
      // 提交成功提示
  
      
      // 这里可以添加表单提交的逻辑，如发送请求到服务器
      console.log('表单数据11：', this.formData);
	      let res= await Setinfo(this.formData);
		  console.log('res系统',res);
		  if(res.code==1){
			      uni.showToast({ title: '提交成功', icon: 'success' });
				  this.imgurl.forEach((item,index)=>{
					  item.url=""
					  item.urls=""
					  item.flg=false
				  })
				   this.formData.station_no="";
				   this.formData.name="";
				   this.formData.province_name="";
				   this.formData.city_name="";
				   this.formData.district_name="";
				   this.formData.address="";
				   this.formData.images="";
				   this.formData.evaluation="";

				   this.imgurlone="";
		  }else{
			      uni.showToast({ title: '提交失败', icon: 'success' });
		  }
    },
	// 选择媒体文件
	  chooseMediaone() {
		  if(this.imgflg==true){
		  			   uni.showToast({ title: '正在上传请稍等', icon: 'success' });
		  }
		  this.imgflg=true;
	// 限制只能选择1张图片
	uni.chooseImage({
	  count: 1, // 只允许上传1张
	  sizeType: ['compressed'], // 只选压缩图，节省流量
	  sourceType: ['album', 'camera'], // 支持相册和相机
	  success: (res) => {
	    // 获取选中的图片临时路径
	    const tempFilePath = res.tempFilePaths[0];
	    this.uploading = true;
	    this.progress = 0;
	    
	    // 上传图片到服务器
	    this.uploadFileone(tempFilePath);
	  },
	  fail: (err) => {
	    console.error('选择图片失败', err);
	    uni.showToast({
	      title: '选择图片失败',
	      icon: 'none'
	    });
	  }
	});
	  },
    // 上传文件到服务器
    uploadFileone(tempFilePath) {
    				  
      uni.uploadFile({
        url:  baseUrl + `common/upload`, // 后端上传接口
        filePath: tempFilePath,
        name: 'file', // 后端接收文件的参数名，需与后端一致
    				  method: 'POST',
    				  header:{
    				  token:localStorage.getItem('token')
    				  },
        // formData: {
        //   // 额外的表单数据，根据后端需求添加
        //   'type': 'image',
        //   'from': 'wechat-h5'
        // },
        // 监听上传进度
        // onProgressUpdate: (res) => {
        //   this.progress = res.progress;
        // },
        success: (uploadRes) => {
          // 解析后端返回结果
          try {
            const result = JSON.parse(uploadRes.data);
            if (result.code === 1 && result.data.fullurl) {
    						  console.log(result.data);
              // 上传成功，保存图片地址
        			  this.formData.evaluation=result.data.url,
        			  // this.imgurls.push(result.data.url)
    				  this.imgurlone=result.data.fullurl
    				  console.log('单独图片',this.imgurlone);
        			  // if(this.imgurl.length==8){
        				 //   this.formData.images=this.imgurl.join();
        				 //   console.log('图片路径',this.formData.images)
        			  // }
        			 
              // this.imageUrl = result.data.fullurl;
              uni.showToast({
                title: '上传成功'
              });
			    this.imgflg=false;
            } else {
				    this.imgflg=false;
              throw new Error(result.msg || '上传失败');
            }
          } catch (e) {
			      this.imgflg=false;
            console.error('上传失败', e);
            uni.showToast({
              title: e.message || '上传失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
			  this.imgflg=false;
          console.error('上传接口调用失败', err);
          uni.showToast({
            title: '网络错误，上传失败',
            icon: 'none'
          });
        },
        complete: () => {
          this.uploading = false;
        }
      });
    },
    // 选择媒体文件
    chooseMedia(e) {
	
		if(this.imgflg==true){
			return;
					   uni.showToast({ title: '正在上传请稍等', icon: 'success' });
		}
		this.imgflg=true;
  // 限制只能选择1张图片
  uni.chooseImage({
    count: 1, // 只允许上传1张
    sizeType: ['compressed'], // 只选压缩图，节省流量
    sourceType: ['album', 'camera'], // 支持相册和相机
    success: (res) => {
      // 获取选中的图片临时路径
      const tempFilePath = res.tempFilePaths[0];
      this.uploading = true;
      this.progress = 0;
      
      // 上传图片到服务器
      this.uploadFile(tempFilePath,e);
	  	this.imgurl[e].flg=true;
    },
    fail: (err) => {
      console.error('选择图片失败', err);
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      });
    }
  });
    },
    // 上传文件到服务器
    uploadFile(tempFilePath,e) {
    				  
      uni.uploadFile({
        url:  baseUrl + `common/upload`, // 后端上传接口
        filePath: tempFilePath,
        name: 'file', // 后端接收文件的参数名，需与后端一致
    				  method: 'POST',
    				  header:{
    				  token:localStorage.getItem('token')
    				  },
        // formData: {
        //   // 额外的表单数据，根据后端需求添加
        //   'type': 'image',
        //   'from': 'wechat-h5'
        // },
        // 监听上传进度
        // onProgressUpdate: (res) => {
        //   this.progress = res.progress;
        // },
        success: (uploadRes) => {
          // 解析后端返回结果
          try {
            const result = JSON.parse(uploadRes.data);
            if (result.code === 1 && result.data.fullurl) {
    						  console.log(result.data);
              // 上传成功，保存图片地址
			  // console.log('e下标',e);
			  // this.imgurl.push({e,url:result.data.fullurl})
			  // console.log('上传图片',this.imgurl);
			  // this.mediaFiles.push({url:result.data.fullurl}),
			  // this.imgurl.push(result.data.url)
			  this.imgurl.forEach((item,index)=>{
				  if(e==index){
					  item.url=result.data.fullurl
				      item.urls=result.data.url
				  }
			  })
			  // 筛选年龄 >= 18 的用户
			    let dataurl='';
			  dataurl =  this.imgurl.filter(user => {
			    return user.urls !="";
			  });
			
			// this.imgurl.forEach((item,index)=>{
			// 				  if(item.urls!=""){
			// 					 dataurl+=item.urls; 
			// 					  // item.url=result.data.fullurl
			// 				   //    item.urls=result.data.url
			// 				  }
			// })
			this.formData.images=dataurl.map((item,index)=>{
				  if(!item.urls){
					  
				  }else{
					  	   return item.urls;
				  }
			
			}).join(',');
			  console.log('dataurl', this.formData.images)
			  // if(this.imgurl.length==8){
				 //   this.formData.images=this.imgurl.join();
				 //   console.log('图片路径',this.formData.images)
			  // }
			 
              // this.imageUrl = result.data.fullurl;
              uni.showToast({
                title: '上传成功'
              });
			  this.imgflg=false;
			  		this.imgurl[e].flg=false;
            } else {
				this.imgflg=false;
              throw new Error(result.msg || '上传失败');
			  	this.imgurl[e].flg=false;
            }
          } catch (e) {
			  this.imgflg=false;
			  	this.imgurl[e].flg=false;
            console.error('上传失败', e);
            uni.showToast({
              title: e.message || '上传失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
			this.imgflg=false;
          console.error('上传接口调用失败', err);
          uni.showToast({
            title: '网络错误，上传失败',
            icon: 'none'
          });
        },
        complete: () => {
          this.uploading = false;
        }
      });
    },
    // 删除媒体文件
    deleteMedia(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个媒体文件吗？',
        success: (res) => {
  this.imgurl.forEach((item,index)=>{
  				  if(e==index){
  					  item.url=""
  					  item.urls=""
  				  }
  })
        }
      });
	  
    },
	deleteMedias(){
		console.log('121212')
		  this.imgurlone='';
		  this.formData.evaluation=""
		// uni.showModal({
		//   title: '确认删除',
		//   content: '确定要删除这个媒体文件吗？',
		//   success: (res) => {
		//     if (res.confirm) {
		//        this.formData.imgurlone='';
		//     }
		//   }
		// });
	}
  }
};
</script>

<style scoped>
.tab-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* Tab导航样式 */
.tab-nav {
  display: flex;
  flex-direction: row;
  height: 88rpx;
  border-bottom: 1px solid #eee;
  background-color: #fff;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
}

.tab-text {
  font-size: 30rpx;
  transition: color 0.3s ease;
}

.tab-item:not(.tab-active) .tab-text {
  color: v-bind(inactiveColor);
}

.tab-active .tab-text {
  color: v-bind(activeColor);
  font-weight: 500;
}

/* 指示器样式 */
.tab-indicator {
  position: absolute;
  bottom: 0;
  width: 40rpx;
  height: 6rpx;
  border-radius: 3rpx;
  background-color: v-bind(activeColor);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.indicator-active {
  transform: scaleX(1);
}

/* 内容区域样式 */
.tab-content {
/*  flex: 1; */
  overflow: hidden;
  position: relative;
  overflow-y: scroll;
  width: 100%;
  height: 2000rpx;
  background-color: #fff;
}

.tab-panel {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: transform 0.3s ease;
  overflow-y: auto;
  padding: 20rpx;
  box-sizing: border-box;
}

.panel-active {
  z-index: 1;
}

.default-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #999;
  font-size: 28rpx;
}

/* 表单样式 */
.form-container {
  padding: 30rpx;
}

.form-item {
  margin-bottom: 40rpx;
}

.form-label {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
  font-size: 28rpx;
}

.required {
  color: #f00;
  margin-right: 5rpx;
}

.form-input {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
}

.form-picker {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  position: relative;
}

.picker-placeholder {
  color: #999;
}

.location-picker {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.location-text {
  color: #333;
}

.location-icon {
  font-size: 36rpx;
}

.submit-button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 10rpx;
  margin-top: 60rpx;
}

/* 上传功能样式 */
.upload-container {
  padding: 30rpx;
}

.upload-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  color: #000;
}
.upload-itemgrid{
	width: 710rpx;
	display: flex;
	flex-wrap: wrap; 
	/* gap: 20rpx; */
}
.upload-grid {
	width: 150rpx;
	height: 170rpx;
	padding: 0 5rpx;
/*  width: 500rpx; */
}

.upload-item {
width: 100%;
	height: 100%;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  overflow: hidden;
  position: relative;
  background-color: #f9f9f9;
}

.upload-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-preview {
  position: relative;
  width: 100%;
  height: 100%;
}

.video-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 40rpx;
  color: #fff;
  text-shadow: 0 0 10rpx rgba(0, 0, 0, 0.5);
}

.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(255, 0, 0, 0.8);
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36rpx;
  line-height: 1;
  border-bottom-left-radius: 8rpx;
}

.upload-add {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.add-icon {
  font-size: 60rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.add-text {
  font-size: 24rpx;
  color: #999;
}
</style>
